<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/8/15
 * Time: 9:14
 */

namespace App\Http\Middleware;

use Closure;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use App\Models\Administrator;
use App\Models\Permission;
use App\Models\Role;

class WebMiddleware extends Middleware
{
    public function handle($request, Closure $next)
    {
        if(!$this->checkLogin()){
            return Response()->json(['code'=>202,'msg'=>'登录已过期，请重新登录']);
        }
        if(!$this->checkStatus()){
            return Response()->json(['code'=>202,'msg'=>'用户已被禁用']);
        }
        
        if(!$this->checkPermission()){
            return Response()->json(['code'=>204,'msg'=>'你没有该权限，访问失败']);
        }
        return $next($request);
    }

    /**
     * 核对登录信息
     * @param $request
     * @return bool
     */
    protected function checkLogin()
    {
        $token = Request()->header('token');
        $cacheMember = Cache::get($token);
        if(!Administrator::where('remember_token',$token)->first()){
            return false;
        }
        if(!$cacheMember){
            Administrator::where('remember_token',$token)->update(['remember_token'=>'']);
            return false;
        }
        return true;
    }
    /**
     * 
     */ 
    protected function checkStatus()
    {
        $token = Request()->header('token');
        $info = Administrator::with(['roles'])->where('remember_token',$token)->first();
        if($info->status != 1){
            return false;
        }
        return true;
    }
    

    /**
     * 核对管理员权限
     * @return bool
     */
    protected function checkPermission()
    {
        $token = Request()->header('token');
        $info = Administrator::with(['roles'])->where('remember_token',$token)->first();
        if($info){
            $roles = $info->toArray()['roles'];
            $permissions = [];
            if($roles) {
                $roleIds = array_column($roles, 'id');
                $permissions = $this->getPermission($roleIds);
            }
            $queryUrl = trim(Request()->getRequestUri(),'/');
            if(in_array('all',$permissions) || in_array($queryUrl,$permissions)){
                return true;
            }
        }
        return false;
    }
    /**
     * 获取权限标识
     * @param array $roleIdArr
     * @return array
     */
    protected function getPermission($roleIdArr = [])
    {
        if(!$roleIdArr){
            return [];
        }
        $permissionSlug = $permissionIdArr = [];
        if (array_search(1, $roleIdArr) !== false) {
            $permissionSlug = ['all'];
        }else{
            $permissionIds = Role::getPermissionId($roleIdArr);
            if($permissionIds){
                $permissionIds = $permissionIds->toArray();
                foreach($permissionIds as $k => $v){
                    $permissionIdArr = array_unique(array_merge($permissionIdArr,$v));
                }
            }
            $slugArr = Permission::whereIn('id',$permissionIdArr)->pluck('slug');
            if($slugArr){
                $permissionSlug = array_merge($permissionSlug,$slugArr->toArray());
            }
        }

        return $permissionSlug;
    }

}
